//
//  KeyframeAnimationVC.m
//  Home
//
//  Created by 曹连华 on 2019/6/28.
//  Copyright © 2019 曹连华. All rights reserved.
//
// 参考链接：https://www.jianshu.com/p/5158b0a33f48

#import "KeyframeAnimationVC.h"
#import "KeyframeAnimationDelegate.h"
#import "KeyframeAnimationViewModel.h"
#import <ServiceCode/ServiceCode.h>
#import <Masonry/Masonry.h>

@interface KeyframeAnimationVC ()<UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) KeyframeAnimationViewModel *viewModel;

@property (nonatomic, strong) UIView *animationView;
@property (nonatomic, strong) UIView *animationContentView;
@property (nonatomic, strong) UIButton *createAnimationType;

@end

@implementation KeyframeAnimationVC

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self.viewModel.dataSource;
        _tableView.estimatedRowHeight = 120;
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    return _tableView;
}

- (UIView *)animationView {
    if (!_animationView) {
        _animationView = [[UIView alloc]init];
        _animationView.backgroundColor = [UIColor blueColor];
        _animationView.layer.shadowOffset = CGSizeMake(0, -10);
        _animationView.layer.shadowColor = [UIColor redColor].CGColor;
        _animationView.layer.shadowOpacity = 1.f;
        _animationView.layer.shadowRadius = 5.f;
        _animationView.layer.cornerRadius = 15.f;
        
    }
    return _animationView;
}

- (UIView *)animationContentView {
    if(!_animationContentView) {
        _animationContentView = [[UIView alloc]init];
        _animationContentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    return _animationContentView;
}
- (UIButton *)createAnimationType {
    if (!_createAnimationType) {
        _createAnimationType = [[UIButton alloc]init];
        _createAnimationType.selected = YES;
        _createAnimationType.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [_createAnimationType setTitle:@"改为Path方式创建动画" forState:UIControlStateNormal];
        [_createAnimationType setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _createAnimationType.titleLabel.font = [UIFont systemFontOfSize:13];
        [_createAnimationType addTarget:self action:@selector(createAnimationTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _createAnimationType;
}

- (KeyframeAnimationViewModel *)viewModel {
    if(!_viewModel) {
        _viewModel = [[KeyframeAnimationViewModel alloc]init];
    }
    return _viewModel;
}

+ (void)load {
    RouterVO *vo = [RouterVO new];
    vo.tab = NO;
    vo.createdType = PBRouteObjectCreateByCode;
    vo.className = NSStringFromClass(self);
    vo.keyInfo = @"关键帧动画示例页面";
    [[Router sharedInstance]registerRouterVO:vo withKey:@"keyframeanimation"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self.tableView reloadData];
}

- (void)initUI {
    self.navigationItem.title = @"KeyframeAnimation";
    
    [self setNaviButtonText:@"恢复原样" textColor:hex(0X2323232) position:BarButtonItemPositionRight];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.animationContentView];
    [self.animationContentView addSubview:self.animationView];
    [self.view addSubview:self.createAnimationType];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.leading.mas_equalTo(0);
        make.width.mas_equalTo(180);
    }];
    
    [self.animationContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.mas_equalTo(self.tableView.mas_right).mas_equalTo(0);
        make.trailing.mas_equalTo(-10);
        make.bottom.mas_equalTo(self.createAnimationType.mas_top).mas_equalTo(-10);
    }];
    
    [self.animationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(10);
        make.top.mas_equalTo(20);
        make.width.height.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    [self.createAnimationType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(-30);
        make.bottom.mas_equalTo(-30);
        make.height.mas_equalTo(40);
    }];
    
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self rightBtnClicked:nil];
    KeyframeAnimationTVCellModel *selectedRow = (KeyframeAnimationTVCellModel *)[self.viewModel.dataSource rowModelAtIndex:indexPath];
    if (selectedRow.isValueCreate) { //Values方式创建动画
       CAKeyframeAnimation *animation =  [self createValuesTypeAnimationWith:selectedRow];
        [self.animationView.layer addAnimation:animation forKey:selectedRow.subTitle];
    } else {//Path方式创建动画
        CAKeyframeAnimation *animation =  [self createPathTypeAnimationWith:selectedRow];
        [self.animationView.layer addAnimation:animation forKey:selectedRow.subTitle];
    }
    
}
- (CAKeyframeAnimation *)createValuesTypeAnimationWith:(KeyframeAnimationTVCellModel *)rowModel {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = rowModel.subTitle;
    animation.values = rowModel.values;
    /**
     * keyTimes的值与values中的值一一对应指定关键帧在动画中的时间点，取值范围为[0,1]。
     * 当keyTimes没有设置的时候,各个关键帧的时间是平分的
     */
    animation.keyTimes = rowModel.keyTimes;
    animation.timingFunctions = rowModel.timingFunctions;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration = 4.0f;
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    animation.delegate = [KeyframeAnimationDelegate new];
    animation.tensionValues = @[@(1),@(0),@(0),@(0),@(0)];
    animation.continuityValues = @[@(-1),@(1),@(-1),@(1),@(-1)];
    animation.biasValues = @[@(1),@(1),@(1),@(1),@(1)];
    animation.calculationMode = kCAAnimationCubic;
    return animation;
}
- (CAKeyframeAnimation *)createPathTypeAnimationWith:(KeyframeAnimationTVCellModel *)rowModel {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = rowModel.subTitle;
    /**
     * keyTimes的值与values中的值一一对应指定关键帧在动画中的时间点，取值范围为[0,1]。
     * 当keyTimes没有设置的时候,各个关键帧的时间是平分的
     */
    animation.keyTimes = rowModel.keyTimes;
    animation.timingFunctions = rowModel.timingFunctions;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration = 4.0f;
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    animation.delegate = [KeyframeAnimationDelegate new];
    animation.tensionValues = @[@(1),@(0),@(0),@(0),@(0)];
    animation.continuityValues = @[@(-1),@(1),@(-1),@(1),@(-1)];
    animation.biasValues = @[@(1),@(1),@(1),@(1),@(1)];
    animation.calculationMode = kCAAnimationCubic;

    UIBezierPath *heartTravelPath = [UIBezierPath bezierPath];
    
    CGMutablePathRef path = CGPathCreateMutable();
    if ([rowModel.subTitle isEqualToString:@"position"]) {//平面移动动画
        for (int i = 0; i < rowModel.values.count; i ++) {
            NSValue *value = [rowModel.values safeObjectAtIndex:i defaultValue:[NSValue valueWithCGPoint:CGPointMake(0, 0)]];
            CGPoint point = value.CGPointValue;
            if (i == 0) {
                CGPathMoveToPoint(path, NULL, self.animationView.centerX,self.animationView.centerY);
                [heartTravelPath moveToPoint:CGPointMake(self.animationView.centerX,self.animationView.centerY)];
            } else {
                CGPathAddLineToPoint(path, NULL, point.x, point.y);
                [heartTravelPath addLineToPoint:point];
            }
            
        }
    }
    animation.path = heartTravelPath.CGPath;//path;
    CGPathRelease(path);
    return animation;
    
}
- (void)vc_reload_TableView {
    [self.tableView reloadData];
}

- (void)rightBtnClicked:(id)sender {
    [self.animationView.layer removeAllAnimations];
}

- (void)createAnimationTypeAction:(UIButton *)btn {
    if (btn.selected) {
        [self.createAnimationType setTitle:@"改为Values方式创建动画" forState:UIControlStateNormal];
    } else {
        [self.createAnimationType setTitle:@"改为Path方式创建动画" forState:UIControlStateNormal];
    }
    btn.selected = !btn.selected;
    [self.viewModel reloadDataSourceIsValuesType:btn.selected];
}
/**
 *
 
 transform.rotation   默认围绕z轴 参数：角度 angle2Radian(4)
 
 transform.rotation.x 围绕x轴翻转 参数：同上
 
 transform.rotation.y 围绕y轴翻转 参数：同上
 
 transform.rotation.z 围绕z轴翻转 参数：同上
 
 transform.scale 所有方向缩放 参数：同上
 
 transform.scale.x x方向缩放 参数：缩放比例 1.5
 
 transform.scale.y y方向缩放 参数：同上
 
 transform.scale.z z方向缩放 参数：同上
 
 transform.translation 移动 参数：移动到的点 （100，100）
 
 transform.translation.x x方向移动 参数：x轴上的坐标 100
 
 transform.translation.y x方向移动 参数：y轴上的坐标
 
 transform.translation.z x方向移动 参数：z轴上的坐标
 
 opacity 透明度 参数：透明度 0.5
 
 backgroundColor 背景颜色 参数：颜色 (id)[[UIColor redColor] CGColor]
 
 cornerRadius 圆角 参数：圆角半径 5
 
 borderWidth 边框宽度 参数：边框宽度 5
 
 bounds 大小 参数：CGRect
 
 contents 内容 参数：CGImage
 
 contentsRect 可视内容 参数：CGRect 值是0～1之间的小数
 
 hidden 是否隐藏
 
 position 平面 参数：CGPoint
 
 position.x
 
 position.y
 
 
 shadowColor
 
 shadowOffset
 
 shadowOpacity
 
 shadowRadius
 
 */
@end
